<?php
header('Content-type: text/csv');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$db = include 'dbConnect.php';
$sql = "SELECT `timestamp`, `value` FROM `readings` WHERE `variable` = '0014'  ORDER BY `timestamp` DESC LIMIT 1440";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error()); 
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $rows[] = $row;
}
for ($i=0; $i<1440; $i++) {
    $row = $rows[1440-$i-1];
    $datetime = $row['timestamp'];
    $value = $row['value'];
    echo '"'.$datetime.'",'.$value."\n";
}
/*
SELECT timestamp  FROM `readings` WHERE `variable` = '0014' ORDER BY timestamp desc limit 20

SELECT * FROM readings WHERE timestamp IN (
SELECT timestamp  FROM `readings` WHERE `variable` = '0014' ORDER BY timestamp desc limit 20)
ORDER BY timestamp asc
#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' 

SELECT * FROM (
  SELECT * FROM readings WHERE variable = '0014' ORDER BY timestamp desc LIMIT 20
}
ORDER BY timestamp ASC
 
 */
?>